package json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonParse {

	public static List<FileGoogleDriver> files = new ArrayList<FileGoogleDriver>();

	public static void createlistFileFromJson(String fileJson) {
		try {
			// read the json file
			FileReader reader = new FileReader(fileJson);
			JSONParser jsonParser = new JSONParser();
			JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

			// get an array from the JSON object
			JSONArray lang = (JSONArray) jsonObject.get("items");

			// take the elements of the json array
			for (int i = 0; i < lang.size(); i++) {
				System.out.println("The " + i + " element of the array: "
						+ lang.get(i));

			}
			Iterator i = lang.iterator();

			// take each value from the json array separately
			while (i.hasNext()) {
				JSONObject innerObj = (JSONObject) i.next();
				String id = (String) innerObj.get("id");
				String title = (String) innerObj.get("title");
				String mimeType = (String) innerObj.get("mimeType");
				FileGoogleDriver f = new FileGoogleDriver(id, title, mimeType);
				files.add(f);
			}

			for (int j = 0; j < files.size(); j++) {
				System.out.println(files.get(j).toJSONString());

			}

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ParseException ex) {
			ex.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
	}

	public static User createuserJson(String fileJson) {
		User user=null;
		try {
			// read the json file
			FileReader reader = new FileReader(fileJson);
			JSONParser jsonParser = new JSONParser();
			JSONObject innerObj = (JSONObject) jsonParser.parse(reader);

			String id = (String) innerObj.get("id");
			String name = (String) innerObj.get("name");
			String email = (String) innerObj.get("email");
			
			user= new User(id, name, email);
			user.setPicture((String) innerObj.get("picture"));
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ParseException ex) {
			ex.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		return user;

	}
}
